package com.brillilab.starter.controller.aio.user;

import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils;
import com.brillilab.common.constant.ResultEnum;
import com.brillilab.common.entity.ResponseVo;
import com.brillilab.common.utils.ValidatorUtil;
import com.brillilab.domain.enums.lab.LabMemberEnum;
import com.brillilab.domain.enums.lab.UserInviteAuditStateEnum;
import com.brillilab.domain.po.lab.LabMember;
import com.brillilab.domain.po.user.UserInviteAudit;
import com.brillilab.domain.po.user.Users;
import com.brillilab.domain.vo.lab.ApplyJoinLabVo;
import com.brillilab.domain.vo.user.UserInviteApplyInfoVo;
import com.brillilab.service.core.email.impl.EmailServiceImpl;
import com.brillilab.service.core.lab.ILabMemberService;
import com.brillilab.service.core.system.ISystemConfigService;
import com.brillilab.service.core.user.IUserInviteAuditService;
import com.brillilab.service.logic.crm.CrmUsersLogic;
import com.brillilab.service.logic.lab.LabApplyLogic;
import com.brillilab.service.logic.message.MessageLogic;
import com.brillilab.service.logic.user.UserInviteAuditLogic;
import com.brillilab.service.logic.user.UsersLogic;
import com.brillilab.starter.aspect.AspectLog;
import com.brillilab.starter.constant.StarterConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * @author zlb
 * @Title: UserInviteRegAuditController
 * @ProjectName brill_lab
 * @Description: TODO
 * @date 2019/7/3 9:36
 */
@Slf4j
@RestController
@RequestMapping("/api/userInviteAudit")
public class UserInviteRegAuditController {

    @Resource
    private UsersLogic usersLogic;

    @Resource
    private IUserInviteAuditService userInviteAuditService;

    @Resource
    private UserInviteAuditLogic userInviteAuditLogic;

    @Resource
    private CrmUsersLogic crmUsersLogic;

    @Resource
    private MessageLogic messageLogic;

    @Resource
    private EmailServiceImpl emailService;
    @Resource
    private ILabMemberService labMemberService;
    @Resource
    private LabApplyLogic labApplyLogic;
    @Resource
    private ISystemConfigService systemConfigService;

    /**
     * 邀请注册验证
     *
     * @return
     */
    @GetMapping("/checkInviteReg")
    public ResponseVo checkInviteReg(String checkCode) {
        String decodeStr = null;
        try {
            decodeStr = new String(Base64.getUrlDecoder().decode(checkCode), "utf-8");
        } catch (UnsupportedEncodingException e) {
            log.info("邀请码---》" + checkCode + " base64解密失败");
        }
        String[] array = decodeStr.split("_");
        Assert.isTrue(array.length == 2, ResultEnum.REQUEST_PARAM_LACK.getMessage());
        Long id = Long.parseLong(array[0]);
        String code = array[1];
        Assert.isTrue(StringUtils.isNotBlank(code), ResultEnum.REQUEST_PARAM_LACK.getMessage());
        return userInviteAuditLogic.getUserInviteAudit(id, code.trim());
    }

    /**
     * 提交实验室成员邀请审核
     *
     * @param userInviteApplyInfoVo
     * @return
     */
    @AspectLog
    @PostMapping("/submitLabMemberAudit")
    public ResponseVo submitLabMemberAudit(@RequestBody UserInviteApplyInfoVo userInviteApplyInfoVo) {
        Assert.isTrue(userInviteApplyInfoVo.getApplyId() != null, "邀请Id不能为空！");
        Assert.isTrue(!userInviteApplyInfoVo.getApplyId().equals(0L), "邀请Id参数有误！");
        Assert.isTrue(StringUtils.isNotEmpty(userInviteApplyInfoVo.getMobile()), "手机号不能为空！");
        Assert.isTrue(userInviteApplyInfoVo.getMobile().length() == 11, "手机号长度有误！");
        Assert.isTrue(StringUtils.isNotEmpty(userInviteApplyInfoVo.getRealName()), "姓名不能为空！");
        Assert.isTrue(userInviteApplyInfoVo.getMobile().length() <= 50, "姓名参数字符过长！");
        Assert.isTrue(userInviteApplyInfoVo.getDuty() != null, "职务参数不能为空！");
        Assert.isTrue(!userInviteApplyInfoVo.getDuty().equals(0), "职务参数有误！");

        UserInviteAudit userInviteAudit = userInviteAuditService.selectById(userInviteApplyInfoVo.getApplyId());
        Assert.notNull(userInviteAudit, "成员邀请信息不存在！");

        Users user = usersLogic.getUser(userInviteApplyInfoVo.getMobile());
        if (user == null) {
            Assert.isTrue(StringUtils.isNotEmpty(userInviteApplyInfoVo.getPassword()), "密码不能为空！");
            Assert.isTrue(StringUtils.isNotEmpty(userInviteApplyInfoVo.getSecurityPwd()), "数据密码不能为空！");
        } else {
            if (user.getLabId() != null && user.getLabId() > 0) {
                ResponseVo failure;
                //用户存在，且在当前实验室
                LabMember labMember = labMemberService.selectMember(userInviteAudit.getLabId(), user.getId());
                if (labMember != null && LabMemberEnum.State.STATE_IN.getValue().equals(labMember.getState())) {
                    //提示已加入当前实验室
                    failure = ResponseVo.failure(ResultEnum.USER_EXIST_CURRENT_LAB.getMessage());
                    failure.setCode(ResultEnum.USER_EXIST_CURRENT_LAB.getCode());
                    return failure;
                }
            }

            //已注册用户登录密码和数据密码赋值为空字符
            userInviteApplyInfoVo.setPassword("");
            userInviteApplyInfoVo.setSecurityPwd("");
        }

        //机构邮箱验证码检测
        if (StringUtils.isNotEmpty(userInviteApplyInfoVo.getOrgEmail())) {
            String orgEmail = userInviteApplyInfoVo.getOrgEmail();
            Assert.isTrue(ValidatorUtil.isEmail(orgEmail), "请输入正确格式的邮箱！");
            boolean isRightEmail = labApplyLogic.checkEmailFormat(orgEmail);
            Assert.isTrue(isRightEmail, "非学术机构邮箱，禁止提交申请！");
        }

        UserInviteAudit apply = userInviteAuditLogic.submitLabMemberApply(userInviteApplyInfoVo, null);
        if (apply != null && apply.getId() > 0) {
            if (apply.getState().equals(UserInviteAuditStateEnum.AUDIT_PASS.getValue())) {
                return ResponseVo.success("加入实验室成功", "加入实验室成功");
            } else if (apply.getState().equals(UserInviteAuditStateEnum.WAIT_CHECK.getValue())) {
                return ResponseVo.success("验证信息已经发送到您的邮箱，请您在邮箱中点击链接验证", "验证信息已经发送到您的邮箱，请您在邮箱中点击链接验证");
            } else if (apply.getState().equals(UserInviteAuditStateEnum.WAIT_AUDIT.getValue())) {
                return ResponseVo.failure(ResultEnum.LAB_NO_PI_OR_LAB_AUDIT_WAIT_PC, "您的申请已经提交成功！我们会在1—3个工作日内审核完成，审核完成后会短信通知您，请您耐心等待。", "您的申请已经提交成功！我们会在1—3个工作日内审核完成，审核完成后会短信通知您，请您耐心等待。");
            } else {
                return ResponseVo.failure("状态异常:" + apply.getState());
            }
        } else {
            return ResponseVo.failure("提交申请失败");
        }
    }

    /**
     * 添加实验室成员
     *
     * @param userInviteApplyInfoVo
     * @param token
     * @return
     */
    @AspectLog
    @PostMapping("/addLabMemberAudit")
    public ResponseVo addLabMemberAudit(@RequestBody UserInviteApplyInfoVo userInviteApplyInfoVo, @RequestHeader(name = StarterConstant.TOKEN) String token) {
        Users user = usersLogic.getUser(userInviteApplyInfoVo.getMobile());
        Assert.isTrue(StringUtils.isNotEmpty(userInviteApplyInfoVo.getMobile()), "手机号不能为空！");
        Assert.isTrue(ValidatorUtil.isPhone(userInviteApplyInfoVo.getMobile()), "手机号格式错误");
        Assert.isTrue(StringUtils.isNotEmpty(userInviteApplyInfoVo.getRealName()), "姓名不能为空！");
        Assert.isTrue(StringUtils.isNotBlank(userInviteApplyInfoVo.getSmsCode()), "短信验证码不能为空！");
        Assert.isTrue(userInviteApplyInfoVo.getDuty() != null, "职务参数不能为空！");
        Assert.isTrue(!userInviteApplyInfoVo.getDuty().equals(0), "职务参数有误！");
        if (user == null) {
            Assert.isTrue(StringUtils.isNotEmpty(userInviteApplyInfoVo.getPassword()), "密码不能为空！");
            Assert.isTrue(StringUtils.isNotEmpty(userInviteApplyInfoVo.getSecurityPwd()), "数据密码不能为空！");
        }

        return usersLogic.validateMemberInfo(userInviteApplyInfoVo, user, token);
    }


    /**
     * 申请加入实验室
     *
     * @param applyJoinLabVo
     * @return
     */
    @AspectLog
    @PostMapping("/applyJoinLab")
    public ResponseVo applyJoinLab(@RequestBody ApplyJoinLabVo applyJoinLabVo) {
        Users user = usersLogic.getUser(applyJoinLabVo.getMobile());
        Assert.isTrue(StringUtils.isNotEmpty(applyJoinLabVo.getMobile()), "手机号不能为空！");
        Assert.isTrue(ValidatorUtil.isPhone(applyJoinLabVo.getMobile()), "手机号格式错误");
        Assert.isTrue(StringUtils.isNotEmpty(applyJoinLabVo.getRealName()), "姓名不能为空！");
        Assert.isTrue(applyJoinLabVo.getLabId() != null, "实验室ID不能为空！");
        Assert.isTrue(!applyJoinLabVo.getLabId().equals(0), "实验室ID有误！");
        if (user == null) {
            Assert.isTrue(StringUtils.isNotEmpty(applyJoinLabVo.getPassword()), "密码不能为空！");
            Assert.isTrue(StringUtils.isNotEmpty(applyJoinLabVo.getSecurityPwd()), "数据密码不能为空！");
        }

        if (user != null) {
            boolean isHaveLab = labApplyLogic.CheckPIUser(user);
            Assert.isTrue(isHaveLab, "此用户已经是PI，无法加入其它实验室！");

            //检测用户是否已经加入当前实验室
            if (user.getLabId() != null && user.getLabId() > 0) {
                ResponseVo failure;
                LabMember labMember = labMemberService.selectMember(applyJoinLabVo.getLabId(), user.getId());
                if (labMember != null && labMember.getState().equals(LabMemberEnum.State.STATE_IN.getValue())) {
                    //提示已加入当前实验室
                    failure = ResponseVo.failure(ResultEnum.USER_EXIST_CURRENT_LAB.getMessage());
                    failure.setCode(ResultEnum.USER_EXIST_CURRENT_LAB.getCode());
                    return failure;
                }
            }
            //已注册用户登录密码和数据密码赋值为空字符
            applyJoinLabVo.setPassword("");
            applyJoinLabVo.setSecurityPwd("");
        }

        //机构邮箱验证码检测
        if (StringUtils.isNotEmpty(applyJoinLabVo.getOrgEmail())) {
            String orgEmail = applyJoinLabVo.getOrgEmail();
            Assert.isTrue(ValidatorUtil.isEmail(orgEmail), "请输入正确格式的邮箱！");
            boolean isRightEmail = systemConfigService.checkEmailFormat(orgEmail);
            Assert.isTrue(isRightEmail, "非学术机构邮箱，禁止提交申请！");
        }

        UserInviteAudit apply = userInviteAuditLogic.submitApplyJoinLab(applyJoinLabVo);
        if (apply != null && apply.getId() > 0) {
            if (apply.getState().equals(UserInviteAuditStateEnum.AUDIT_PASS.getValue())) {
                return ResponseVo.success("您已成功加入"+apply.getLabName()+"，请您在客户端登录。", "您已成功加入"+apply.getLabName()+"，请您在客户端登录。");
            } else if (apply.getState().equals(UserInviteAuditStateEnum.WAIT_CHECK.getValue())) {
                return ResponseVo.success("验证信息已经发送到您的邮箱，请您在邮箱中点击链接验证", "验证信息已经发送到您的邮箱，请您在邮箱中点击链接验证");
            } else if (apply.getState().equals(UserInviteAuditStateEnum.WAIT_AUDIT.getValue())) {
                return ResponseVo.failure(ResultEnum.LAB_NO_PI_OR_LAB_AUDIT_WAIT_PC, "您的申请已经提交成功！我们会在1—3个工作日内审核完成，审核完成后会短信通知您，请您耐心等待。", "您的申请已经提交成功！我们会在1—3个工作日内审核完成，审核完成后会短信通知您，请您耐心等待。");
            } else {
                return ResponseVo.failure("状态异常:" + apply.getState());
            }
        } else {
            return ResponseVo.failure("提交申请失败");
        }
    }
}

